package net.redxyz.open.api.manage.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.dbo.Selector;

import net.redxyz.open.api.OpenApiService;
import net.redxyz.open.api.dbo.AppApiForbid;
import net.redxyz.open.api.dbo.AppApiStat;

/**
 * 
 * 开放API相关ajax调用
 * 
 * @version v7.0.1 @author lgz 2021-10-21 新建与整理
 */
@AnAlias("OpenApiPresenter")
public class OpenApiPresenter
{
    /**
     * 查询API条件
     * 
     * @param appKey 应用ID
     * @param apiMethod 方法名，可选
     * @throws Exception
     */
    public static void doQueryForbidApi(HttpRequest request) throws Exception
    {//
    
        String apiMethod = request.getParameter("apiMethod");
        long appKey = request.getParameterLong("appKey");
        List<AppApiForbid> list = new ArrayList<>();
        if (appKey > 0)
        {//
            Selector sel = new Selector();
            sel.addMust("appKey", appKey);
            if (Validates.isNotEmptyBlank(apiMethod))
                sel.addMust("apiMethod", apiMethod);
            
            sel.addOrderbyDesc("apiState,updateTime");
            list = ORM.table().list(AppApiForbid.class, sel);
        }
        
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("apiList", list);
        request.setResponseResult(Jsons.toString(dataMap));
    }
    
    /**
     * 初始化 禁用API
     * 
     * @param request
     * @throws Exception
     */
    public static void doInitForbidApi(HttpRequest request) throws Exception
    {
        OpenApiService.doInitForbidApi(request.getParameterLong("appKey"));
    }
    
    /**
     * 开启或关闭 API
     * 
     * @param request
     * @throws Exception
     */
    public static void doOpenOrForbidApi(HttpRequest request) throws Exception
    {
        long appKey = request.getParameterLong("appKey");
        String method = Strings.trim(request.getParameter("method"));
        String desc = Strings.trim(request.getParameter("desc"));
        int opType = request.getParameterInt("opType");
        if (appKey <= 0 || Validates.isEmptyBlank(method))
        {
            request.setResponseError("无效的appKey或者method");
            return;
        }
        
        if (Validates.isEmptyBlank(desc) || desc.length() > 1024)
        {
            request.setResponseError("描述不能为空白，且不能超过1024字符");
            return;
        }
        
        if (opType == 1)
            OpenApiService.doRelieveForbidApi(appKey, method, desc);
        else
            OpenApiService.doForbidApi(appKey, method, desc);
    }
    
    /**
     * 添加禁止调用API
     * 
     * @param request
     * @throws Exception
     */
    public static void doAddForbidApi(HttpRequest request) throws Exception
    {
        long appKey = request.getParameterLong("appKey");
        String method = Strings.trim(request.getParameter("method"));
        String desc = Strings.trim(request.getParameter("desc"));
        String apiDesc = Strings.trim(request.getParameter("apiDesc"));
        if (appKey <= 0 || Validates.isEmptyBlank(method))
        {
            request.setResponseError("无效的appKey或者method");
            return;
        }
        
        if (Validates.isEmptyBlank(desc) || desc.length() > 1024)
        {
            request.setResponseError("描述不能为空白，且不能超过1024字符");
            return;
        }
        
        if (Validates.isEmptyBlank(apiDesc) || apiDesc.length() > 1024)
        {
            request.setResponseError("API场景描述不能为空，且不能超过24字符");
            return;
        }
        
        OpenApiService.doAddForbidApi(appKey, method, apiDesc, desc);
    }
    
    /**
     * 删除禁止API
     * 
     * @param request
     * @throws Exception
     */
    public static void doDeleteForbidApi(HttpRequest request) throws Exception
    {
        
        long appKey = request.getParameterLong("appKey");
        String method = Strings.trim(request.getParameter("method"));
        if (appKey <= 0 || Validates.isEmptyBlank(method))
        {
            request.setResponseError("无效的appKey或者method");
            return;
        }
        
        ORM.get(ZTable.class).delete(AppApiForbid.class, new Selector("appKey", appKey).addMust("apiMethod", method));
    }
    
    /**
     * 查询统计信息
     * 
     * @param request
     * @throws Exception
     */
    public static void doInvokeApiStat(HttpRequest request) throws Exception
    {
        long appKey = request.getParameterLong("appKey");
        if (appKey <= 0)
        {
            request.setResponseError("无效的appKey或者method");
            return;
        }
        
        int page = request.getParameterInt("page");
        int pageSize = request.getParameterInt("pageSize");
        if (page <= 1)
            page = 1;
        if (pageSize <= 10)
            pageSize = 10;
        
        String startDate = request.getParameter("startDate");// 默认查询前30天的数据
        String endDate = request.getParameter("endDate");
        
        if (!Validates.isDate(endDate))
            endDate = DateTimes.getDateString();
        
        if (Validates.isEmptyBlank(startDate))
            startDate = DateTimes.getPreviousDateString(endDate, 30);
        
        if (!Validates.isDate(startDate))
        {
            request.setResponseError("无效结束开始时间。");
            return;
        }
        
        int day = DateTimes.compareDay(endDate, startDate);
        if (day <= 0)
        {
            request.setResponseError("开始时间必须小于结束时间");
            return;
        }
        
        List<Integer> dayList = new ArrayList<Integer>();
       
        for (int i = 0; i <= day; i++)
        {
            String day_str = DateTimes.getNextDateString(startDate, i);
            int day_int = Integer.parseInt(day_str.replaceAll("-", ""));
            dayList.add(day_int);
        }
        
        int[] days = Arrays.toArrayInt(dayList);
        
        Selector select = new Selector("appId", appKey).addMustIn("dayDate", days).addOrderbyDesc("dayDate");
        PageResult<AppApiStat> pageResult = ORM.get(ZTable.class).page(AppApiStat.class, page, pageSize, select);
        
        // 条件下总调用量
        long[] sums = ORM.get(ZTable.class).sum(AppApiStat.class, select, "callApiCount", "callApiSuccCount", "callApiFailCount", "tradePullCount");
        
        // 响应客户端
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", pageResult.list());
        dataMap.put("total", pageResult.total());
        dataMap.put("hasNext", pageResult.hasNext());
        dataMap.put("callApiCount", sums[0]);
        dataMap.put("callApiSuccCount", sums[1]);
        dataMap.put("callApiFailCount", sums[2]);
        dataMap.put("tradePullCount", sums[3]);
        
        request.setResponseResult(Jsons.toString(dataMap));
    }
}
